<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Book extends Model{

	/**
	 * 关联到模型的数据表
	 *
	 * @var string
	 */
	protected $table = 'dqm_book';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'book_title'
	];

	/**
	 * 字段：笔记本唯一标识
	 */
	const FIELD_BOOK_ID 		= 'book_id';


	/**
	 * 字段：用户唯一标识
	 */
	const FIELD_USER_ID 		= 'user_id';

	/**
	 * 字段：笔记本标题
	 */
	const FIELD_BOOK_TITLE 		= 'book_title';

	/**
	 * 字段：标记删除，0：正常，1：标记删除
	 */
	const FIELD_TRASH 			= 'trash';

	/**
	 * 字段：创建时间
	 */
	const FIELD_CREATED_TIME 	= 'created_time';

	/**
	 * 字段：更新时间
	 */
	const FIELD_UPDATED_TIME 	= 'updated_time';

	/**
	 * 笔记本删除状态: 1、标记删除 ; 0、正常
	 */
	const ENABLE_TRASH_STATUS = 1;
	const DISABLE_TRASH_STATUS = 0;

	/**
	 * 根据笔记本ID获取正常状态的笔记信息
	 *
	 * @param $book_id
	 * @param array $select_fields
	 * @return mixed
	 */
	static public function getNormalBookByBookId($book_id, $select_fields = []){
		$conditions['where'][self::FIELD_BOOK_ID] = $book_id;
        $result = Book::select($select_fields)->where($conditions['where'])->active()->get();
		return $result;
	}

	/**
	 *  获取当前用户下的所有正常笔记本列表
	 *
	 * @param $user_id
	 * @param string $search_book
	 * @param array $select_fields
	 * @return mixed
	 */
	static public function getBooksByUserId($user_id, $search_book = '', $select_fields = []){
		$conditions['where'][self::FIELD_USER_ID] = $user_id;
		if($search_book){
			$result = Book::select($select_fields)->where($conditions['where'])->where(self::FIELD_BOOK_TITLE, 'LIKE', '%'.$search_book.'%')->active()->get();
		}else{
			$result = Book::select($select_fields)->where($conditions['where'])->active()->get();
		}
		return $result;
	}

	/**
	 * 根据查询条件获取笔记本个数
	 *
	 * @param array $conditions
	 * @return mixed
	 */
	static function getBookCountByConditions($conditions = []){
		$result = Book::where($conditions['where'])->count();
		return $result;
	}

	/**
	 * 添加一条笔记本
	 *
	 * @param array $data
	 * @return bool|null
	 */
	static public function add($data = []){
		if(!empty($data)){
			$now = date('Y-m-d H:i:s', time());
			if(!isset($data[self::FIELD_CREATED_TIME])){
				$data[self::FIELD_CREATED_TIME] = $now;
			}
			if(!isset($data[self::FIELD_UPDATED_TIME])) {
				$data[self::FIELD_UPDATED_TIME] = $now;
			}
			$book_id = Book::insertGetId($data);
			if($book_id){
				return $book_id;
			}else{
				return false;
			}
		}
		return null;
	}

    /**
     * 根据查询条件获取正常状态的笔记本列表
     *
     * @param $query
     * @return mixed
     */
    public function scopeActive($query){
	    return $query->where(self::FIELD_TRASH, self::DISABLE_TRASH_STATUS)->orderBy(self::FIELD_UPDATED_TIME, 'desc');
    }
}
